package plugin;

import java.awt.AWTException;
import java.awt.Component;
import java.awt.Container;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import robotCross.CrossRobot;
import robotCross.TextMatcher;
import robotCross.TipMatcher;
import abbot.finder.BasicFinder;
import abbot.finder.ComponentNotFoundException;
import abbot.finder.MultipleComponentsFoundException;
import abbot.finder.matchers.ClassMatcher;
import abbot.tester.JComboBoxTester;
import abbot.tester.JFileChooserTester;
import abbot.tester.JTreeLocation;
import abbot.tester.JTreeTester;
import abbot.tester.Robot;
import abbot.util.AWTFixtureHelper;

import com.supermap.data.Dataset;
import com.supermap.data.Datasource;
import com.supermap.data.Point2D;
import com.supermap.desktop.Application;
import com.supermap.desktop.Interface.IDockbar;
import com.supermap.desktop.Interface.IFormMap;
import com.supermap.desktop.Interface.IPopupMenu;
import com.supermap.desktop.implement.SmMenu;
import com.supermap.desktop.implement.SmMenuItem;
import com.supermap.desktop.ui.FrameMenuManager;
import com.supermap.desktop.ui.UICommonToolkit;
import com.supermap.desktop.ui.controls.LayersTree;
import com.supermap.desktop.ui.controls.TreeNodeData;
import com.supermap.desktop.ui.controls.WorkspaceTree;
import com.supermap.mapping.Layer;
import com.supermap.mapping.Map;
import com.supermap.desktop.ui.controls.*;

import command.CmdWorkspaceTree;
import command.Command;
import command.SearchMap;
import command.SearchType;
import commandAction.Action;
import commandAction.ActionUtil;
import commandAction.ActionWorkspaceTree;

public class Activator implements BundleActivator {

	private static BundleContext context;

	public static void setContext(BundleContext context) {
		Activator.context = context;
	}

	public static BundleContext getContext() {
		return Activator.context;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext
	 * )
	 */
	@Override
	public void start(BundleContext bundleContext) throws Exception {
		setContext(bundleContext);
		Application.getActiveApplication().getPluginManager()
				.addPlugin("GUITestPlugin", bundleContext.getBundle());
		System.out.println("GUITestPlugin Running!");
		// t1.start();
		client.start();
		System.out.println("start client thread");
	}

	Thread client = new Thread(new Thread() {
		@Override
		public void run() {
			try {
				Client.connetServer();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (Client.connection != null) {
				// 判断系统，如果不是win32就不需要校验了，校验失败会导致robot的mode设置为AWT，最终不会进行mouseMove操作
				String arch = System.getProperty("os.arch").toLowerCase();
				String os = System.getProperty("os.name").toLowerCase();
				if(!(os.contains("win")&&arch.contains("32"))){
					System.setProperty("abbot.robot.verify","false");
				}
				Action.helper = new AWTFixtureHelper();
				Action.robot = Action.helper.getRobot();
			}
			Client.receive();
		}
	});

	Thread t1 = new Thread(new Thread() {
		@Override
		public void run() {
			Scanner scanner = new Scanner(System.in);
			String msg = null;
			msg = scanner.next();
			Command cmd = new CmdWorkspaceTree();
			SearchMap map = new SearchMap(SearchType.TEXT, "数据源");
			cmd.searchMap.add(map);
			map = new SearchMap(SearchType.TEXT, "Changchun");
			cmd.searchMap.add(map);
			map = new SearchMap(SearchType.TEXT,
					"Factory,Park,Vegetable,Edit_Point");
			cmd.searchMap.add(map);
			Action action = new ActionWorkspaceTree();
			action.action(cmd);
		}
	});
	Thread t = new Thread(new Thread() {
		@Override
		public void run() {

			AWTFixtureHelper helper = new AWTFixtureHelper();
			Robot robot = helper.getRobot();
			robot.delay(5000);
			WorkspaceTree tree1 = UICommonToolkit.getWorkspaceManager()
					.getWorkspaceTree();
			ActionUtil.findTreePath(tree1, null);

			// 删除颜色方案--模态对话框
			JButton button = (JButton) Application.getActiveApplication()
					.getMainFrame().getToolbarManager().get(0).getAt(20);
			helper.getRobot().click(button);
			robot.delay(1000);

			JDialog dialog = (JDialog) KeyboardFocusManager
					.getCurrentKeyboardFocusManager().getFocusedWindow();
			button = (JButton) findComponentByTip(dialog, "删除颜色方案");
			try {
				button = (JButton) new BasicFinder().find(dialog,
						new TipMatcher("删除颜色方案"));
			} catch (ComponentNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (MultipleComponentsFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			helper.getRobot().click(button);
			button = (JButton) findComponentByTip(dialog, "确定");
			robot.click(button);
			robot.delay(1000);

			// 工作空间树--右键菜单
			WorkspaceTree tree = UICommonToolkit.getWorkspaceManager()
					.getWorkspaceTree();
			DefaultMutableTreeNode dsNode = tree.getDatasourcesNode();
			JTreeTester treeTester = new JTreeTester();
			treeTester.actionSelectPath(tree, new TreePath(dsNode.getPath()));
			new CrossRobot().click(InputEvent.BUTTON3_MASK);
			robot.delay(500);
			IPopupMenu menu = Application
					.getActiveApplication()
					.getMainFrame()
					.getContextMenuManager()
					.get("SuperMap.Desktop.UI.WorkspaceControlManager.ContextMenuDatasources");
			robot.click((Component) menu.getAt(0));
			robot.delay(1000);

			// 文件选择器--打开数据源
			dialog = (JDialog) KeyboardFocusManager
					.getCurrentKeyboardFocusManager().getFocusedWindow();
			JFileChooser fileChooser = null;
			try {
				fileChooser = (JFileChooser) new BasicFinder().find(dialog,
						new ClassMatcher(JFileChooser.class));
			} catch (ComponentNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (MultipleComponentsFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			JFileChooserTester chooserTester = new JFileChooserTester();
			File file = new File("F:/SampleData711/City/Changchun.udb");
			chooserTester.actionSetSelectedFile(fileChooser, file);
			robot.delay(500);
			chooserTester.actionApprove(fileChooser);

			// 打开数据集
			TreePath treePath = this.getDatasetTreePath("Changchun", "Factory");
			treeTester.actionSelectPath(tree, treePath);
			new CrossRobot().doubleClick(InputEvent.BUTTON1_MASK);
			robot.delay(2000);

			// 图层管理器
			LayersTree layersTree = UICommonToolkit.getLayersManager()
					.getLayersTree();
			IFormMap formMap = (IFormMap) Application.getActiveApplication()
					.getActiveForm();
			Layer layer = formMap.getMapControl().getMap().getLayers().get(0);
			// DefaultMutableTreeNode layerNode =
			// layersTree.getNodeByLayer(layer);
			DefaultMutableTreeNode layerNode = null;
			treePath = new TreePath(layerNode.getPath());
			treeTester.actionClick(layersTree, new JTreeLocation(treePath));
			robot.delay(500);
			new CrossRobot().click(InputEvent.BUTTON3_MASK);
			robot.delay(500);
			menu = Application
					.getActiveApplication()
					.getMainFrame()
					.getContextMenuManager()
					.get("SuperMap.Desktop.UI.LayersControlManager.LayerVectorContextMenu");
			robot.click((Component) menu.getAt(11));
			robot.delay(1500);

			// 制作专题图
			dialog = (JDialog) KeyboardFocusManager
					.getCurrentKeyboardFocusManager().getFocusedWindow();
			JList list = (JList) this.findComponentByClass(dialog, JList.class);
			list.getSelectionModel().setSelectionInterval(2, 2);
			robot.delay(300);
			dialog = (JDialog) KeyboardFocusManager
					.getCurrentKeyboardFocusManager().getFocusedWindow();
			JComponent label = null;
			try {
				label = (JComponent) new BasicFinder().find(dialog,
						new TextMatcher("分段风格"));
			} catch (ComponentNotFoundException
					| MultipleComponentsFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.click(label);
			button = (JButton) findComponentByTip(dialog, "确定");
			robot.click(button);
			robot.delay(1000);

			// 设置专题图属性--docbar
			IDockbar dockBar = (Dockbar) Application.getActiveApplication()
					.getMainFrame().getDockbarManager().get(5);
			JComboBox jc = (JComboBox) this.findComponentByText(
					(JComponent) dockBar, "表达式:");
			JComboBoxTester comboBoxTester = new JComboBoxTester();
			comboBoxTester.actionSelectItem(jc, "SmX");

			// 地图操作
			Map map = formMap.getMapControl().getMap();
			Point point = map.mapToPixel(new Point2D(4701.02648, -3846.94109));
			robot.mouseMove(formMap.getMapControl(), point.x, point.y);
			robot.delay(1000);
			try {
				new java.awt.Robot().mouseWheel(50);
				robot.delay(1000);
				new java.awt.Robot().mouseWheel(20);
				robot.delay(1000);
			} catch (AWTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			new CrossRobot().click(InputEvent.BUTTON3_MASK);
			robot.delay(1000);

			// 菜单栏
			JMenuBar menuBar = ((FrameMenuManager) Application
					.getActiveApplication().getMainFrame()
					.getFrameMenuManager()).getMenuBar();
			// searchComponents(menuBar);
			SmMenu menuButton = null;
			try {
				menuButton = (SmMenu) new BasicFinder().find(menuBar,
						new TextMatcher("地图"));
			} catch (ComponentNotFoundException
					| MultipleComponentsFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.click(menuButton);
			robot.delay(2000);
			JPopupMenu frameMenu = menuButton.getPopupMenu();
			try {
				menuButton = (SmMenu) new BasicFinder().find(frameMenu,
						new TextMatcher("地图浏览"));
			} catch (ComponentNotFoundException
					| MultipleComponentsFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.click(menuButton);
			robot.delay(1000);
			frameMenu = menuButton.getPopupMenu();
			SmMenuItem item = null;
			try {
				item = (SmMenuItem) new BasicFinder().find(frameMenu,
						new TextMatcher("全幅显示"));
			} catch (ComponentNotFoundException
					| MultipleComponentsFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.click(item);
			robot.delay(1000);

		}

		public List<Component> searchComponents(Container c) {
			List<Component> components = new ArrayList<Component>();
			if (c == null)
				return components;
			for (int i = 0; i < c.getComponents().length; i++) {
				components.add(c.getComponent(i));
				Application.getActiveApplication().getOutput()
						.output(c.getComponent(i).toString());
				if (c.getComponent(i) instanceof Container) {
					components.addAll(searchComponents((Container) c
							.getComponent(i)));
				}
			}
			return components;
		}

		public List<Component> searchComponents(JComponent c) {
			List<Component> components = new ArrayList<Component>();
			if (c == null)
				return components;
			for (int i = 0; i < c.getComponents().length; i++) {
				components.add(c.getComponent(i));
				Application.getActiveApplication().getOutput()
						.output(c.getComponent(i).toString());
				if (c.getComponentCount() > 0
						&& c.getComponent(i) instanceof JComponent) {
					components.addAll(searchComponents((JComponent) c
							.getComponent(i)));
				}
			}
			return components;
		}

		// 用扩展robot的crossRobot包中的tipMacher替代，这个方法暂时不删，tipMacher不行的时候也许会用
		public Component findComponentByTip(Container container, String tip) {
			Component c = null;
			if (container == null || tip == null)
				return c;
			for (int i = 0; i < container.getComponents().length; i++) {
				if (container.getComponent(i) instanceof JComponent
						&& tip.equals(((JComponent) container.getComponent(i))
								.getToolTipText())) {
					return container.getComponent(i);
				} else if (container.getComponent(i) instanceof Container) {
					c = findComponentByTip(
							(Container) container.getComponent(i), tip);
					if (c != null)
						return c;
				}
			}
			return c;
		}

		public Component findComponentByText(JComponent jc, String text) {
			Component c = null;
			if (jc == null || text == null)
				return c;
			for (int i = 0; i < jc.getComponents().length; i++) {
				if (jc.getComponent(i) instanceof JLabel) {
					if (text.equals(((JLabel) jc.getComponent(i)).getText())
							&& jc.getComponent(i).isShowing() == true) {
						if (i < jc.getComponents().length - 1) {
							return jc.getComponent(i + 1);
						}
					}
				} else if (jc.getComponentCount() > 0
						&& jc.getComponent(i) instanceof JComponent) {
					c = findComponentByText((JComponent) jc.getComponent(i),
							text);
					if (c != null) {
						return c;
					}
				}
			}
			return c;
		}

		public Component findComponentByClass(Container container, Class cl) {
			Component c = null;
			if (container == null || cl == null)
				return c;
			for (int i = 0; i < container.getComponents().length; i++) {
				if (isType(container.getComponent(i).getClass(), cl)) {
					return container.getComponent(i);
				} else if (container.getComponent(i) instanceof Container) {
					c = findComponentByClass(
							(Container) container.getComponent(i), cl);
					if (c != null)
						return c;
				}
			}
			return c;
		}

		public Boolean isType(Class c, Class type) {
			if (c == type)
				return true;
			else if (c != Object.class && c.getSuperclass() != Object.class) {
				return isType(c.getSuperclass(), type);
			}
			return false;
		}

		// 获取某个数据源节点的treePath
		public TreePath getDSTreePath(String dsName) {
			if (dsName == null)
				return null;
			WorkspaceTree tree = UICommonToolkit.getWorkspaceManager()
					.getWorkspaceTree();
			DefaultMutableTreeNode dsNode = tree.getDatasourcesNode();
			for (int i = 0; i < dsNode.getChildCount(); i++) {
				TreeNodeData data = (TreeNodeData) ((DefaultMutableTreeNode) dsNode
						.getChildAt(i)).getUserObject();
				Datasource ds = (Datasource) data.getData();
				if (dsName.equals(ds.getAlias())) {
					TreePath path = new TreePath(
							((DefaultMutableTreeNode) dsNode.getChildAt(i))
									.getPath());
					return path;
				}
			}
			return null;
		}

		public TreePath getDatasetTreePath(String dsName, String datasetName) {
			if (dsName == null || datasetName == null)
				return null;
			WorkspaceTree tree = UICommonToolkit.getWorkspaceManager()
					.getWorkspaceTree();
			DefaultMutableTreeNode dsNode = tree.getDatasourcesNode();
			for (int i = 0; i < dsNode.getChildCount(); i++) {
				TreeNodeData data = (TreeNodeData) ((DefaultMutableTreeNode) dsNode
						.getChildAt(i)).getUserObject();
				Datasource ds = (Datasource) data.getData();
				System.out.println(ds.getAlias() + "");
				if (dsName.equals(ds.getAlias())) {
					for (int j = 0; j < dsNode.getChildAt(i).getChildCount(); j++) {
						TreeNodeData data1 = (TreeNodeData) ((DefaultMutableTreeNode) dsNode
								.getChildAt(i).getChildAt(j)).getUserObject();
						Dataset dataset = (Dataset) data1.getData();
						if (datasetName.equals(dataset.getName())) {
							TreePath path = new TreePath(
									((DefaultMutableTreeNode) dsNode
											.getChildAt(i).getChildAt(j))
											.getPath());
							return path;
						}
					}
				}
			}
			return null;
		}
	});

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	@Override
	public void stop(BundleContext bundleContext) throws Exception {
		setContext(null);
	}
}
